import React, { useState } from "react";
import {
  View,
  Text,
  ActivityIndicator,
  FlatList,
  TouchableOpacity,
  Image,
  StyleSheet,
} from "react-native";
import { Stack } from "expo-router";
import SearchUserBar from "@/components/Friend/SearchUserBar";
import { useTheme } from "@/contexts/ThemeContext";
import { UserProfileType } from "@/types/user-profile";
import AddFriendCard from "@/components/Friend/AddFriendCard";
import EmptyState from "@/components/Global/EmptyState";
import { Ionicons } from "@expo/vector-icons";
import { searchUserByUUID, searchUserByKeyword } from "@/services/api/user";
import { Page, ResponseCode, Result } from "@/types/api-common";

const AddFriendPage = () => {
  const { colors } = useTheme();
  const [searchType, setSearchType] = useState<"uuid" | "keyword">("uuid"); // 搜索类型
  const [users, setUsers] = useState<UserProfileType[]>([]);
  const [selectedUser, setSelectedUser] = useState<UserProfileType | null>(
    null
  );
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [searchText, setSearchText] = useState<string>(""); // 搜索文本
  const [total, setTotal] = useState<number>(0); // 总用户数
  const [currentPage, setCurrentPage] = useState(1); // 当前页码
  const [hasMore, setHasMore] = useState(true); // 是否还有更多数据
  const [noResults, setNoResults] = useState(false);

  const handleSearch = async (searchText: string, page: number = 1) => {
    if (!searchText) return;

    setIsLoading(true);
    if (page === 1) {
      setUsers([]);
      setSelectedUser(null);
      setError(null);
      setNoResults(false);
    }

    try {
      let res;
      if (searchType === "uuid") {
        res = await searchUserByUUID(searchText);
      } else {
        res = await searchUserByKeyword(searchText, page, 10); // 每页10条数据
      }

      if (res.data.code === ResponseCode.SUCCESS) {
        if (searchType === "keyword") {
          const searchResult: Page<UserProfileType> = res.data.data;
          if (searchResult.records.length === 0) {
            setNoResults(true);
            return;
          }

          setSearchText(searchText); // 更新搜索文本
          setUsers((prevUsers) => [...prevUsers, ...searchResult.records]);
          setTotal(searchResult.total); // 更新总用户数
          setHasMore(currentPage < searchResult.pages); // 如果返回数据为空，则没有更多数据
        } else {
          const searchResult: UserProfileType = res.data.data;
          if (searchResult) {
            setUsers([searchResult]);
            setTotal(1); // UUID 搜索只返回一个用户
          } else {
            setNoResults(true);
          }
        }
      } else {
        setError(res.data.message || "搜索服务出错");
      }
    } catch (e) {
      setError("搜索失败，请稍后再试");
    } finally {
      setIsLoading(false);
    }
  };

  const loadMoreData = async () => {
    if (searchType === "keyword" && hasMore && !isLoading) {
      const nextPage = currentPage + 1;
      setCurrentPage(nextPage);
      await handleSearch(searchText, nextPage);
    }
  };

  const handleSelectUser = (user: UserProfileType) => {
    setSelectedUser(user);
  };

  const handleBackToList = () => {
    setSelectedUser(null);
  };

  const renderUserItem = ({ item }: { item: UserProfileType }) => (
    <TouchableOpacity
      style={styles.userItem}
      onPress={() => handleSelectUser(item)}
    >
      <Image source={{ uri: item.avatar }} style={styles.userAvatar} />
      <View style={styles.userInfo}>
        <Text style={[styles.userName, { color: colors.text.primary }]}>
          {item.nickname}
        </Text>
        <Text style={[styles.userUuid, { color: colors.text.secondary }]}>
          {item.uuid}
        </Text>
      </View>
      <Ionicons name="chevron-forward" size={20} color={colors.text.hint} />
    </TouchableOpacity>
  );

  return (
    <View style={{ flex: 1, backgroundColor: colors.background, padding: 20 }}>
      <Stack.Screen options={{ title: "添加好友" }} />

      {/* 搜索类型切换 */}
      <View style={styles.searchTypeContainer}>
        <TouchableOpacity
          style={[
            styles.searchTypeButton,
            searchType === "uuid" && styles.activeSearchTypeButton,
          ]}
          onPress={() => setSearchType("uuid")}
        >
          <Text
            style={[
              styles.searchTypeText,
              searchType === "uuid" && styles.activeSearchTypeText,
            ]}
          >
            UUID 搜索
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[
            styles.searchTypeButton,
            searchType === "keyword" && styles.activeSearchTypeButton,
          ]}
          onPress={() => setSearchType("keyword")}
        >
          <Text
            style={[
              styles.searchTypeText,
              searchType === "keyword" && styles.activeSearchTypeText,
            ]}
          >
            名称/邮箱搜索
          </Text>
        </TouchableOpacity>
      </View>

      {/* 搜索组件 */}
      <SearchUserBar onSearch={handleSearch} />

      {/* 结果展示区域 */}
      <View style={{ flex: 1 }}>
        {isLoading && (
          <View
            style={{ flex: 1, justifyContent: "center", alignItems: "center" }}
          >
            <ActivityIndicator size="large" color={colors.primary} />
          </View>
        )}

        {!isLoading && error && (
          <Text
            style={{
              marginTop: 20,
              color: colors.status.error,
              textAlign: "center",
            }}
          >
            {error}
          </Text>
        )}

        {!isLoading && noResults && (
          <EmptyState
            icon={
              <Ionicons
                name="search-outline"
                size={50}
                color={colors.text.hint}
              />
            }
            title="未找到用户"
            subtitle="请检查您输入的账号或 UUID 是否正确"
          />
        )}

        {!isLoading && !selectedUser && users.length > 0 && (
          <FlatList
            data={users}
            renderItem={renderUserItem}
            keyExtractor={(item) => item.id}
            contentContainerStyle={{ paddingVertical: 10 }}
            ListHeaderComponent={
              <Text
                style={[styles.resultHeader, { color: colors.text.secondary }]}
              >
                找到 {total} 个用户
              </Text>
            }
            onEndReached={loadMoreData} // 加载更多数据
          />
        )}

        {!isLoading && selectedUser && (
          <View style={{ flex: 1 }}>
            <TouchableOpacity
              style={styles.backButton}
              onPress={handleBackToList}
            >
              <Ionicons name="arrow-back" size={20} color={colors.primary} />
              <Text style={[styles.backText, { color: colors.primary }]}>
                返回列表
              </Text>
            </TouchableOpacity>

            <View style={{ marginTop: 10 }}>
              <AddFriendCard userInfo={selectedUser} />
            </View>
          </View>
        )}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  searchTypeContainer: {
    flexDirection: "row",
    marginBottom: 10,
  },
  searchTypeButton: {
    flex: 1,
    padding: 10,
    borderRadius: 5,
    backgroundColor: "#EEEEEE",
    alignItems: "center",
  },
  activeSearchTypeButton: {
    backgroundColor: "#007AFF",
  },
  searchTypeText: {
    fontSize: 16,
    color: "#333333",
  },
  activeSearchTypeText: {
    color: "white",
    fontWeight: "600",
  },
  userItem: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 12,
    paddingHorizontal: 5,
    borderBottomWidth: 1,
    borderBottomColor: "#EEEEEE",
  },
  userAvatar: {
    width: 50,
    height: 50,
    borderRadius: 8,
  },
  userInfo: {
    flex: 1,
    marginLeft: 15,
  },
  userName: {
    fontSize: 16,
    fontWeight: "600",
  },
  userUuid: {
    fontSize: 14,
    marginTop: 4,
  },
  backButton: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 10,
  },
  backText: {
    fontSize: 16,
    marginLeft: 5,
  },
  resultHeader: {
    marginBottom: 10,
    fontSize: 14,
  },
});

export default AddFriendPage;
